package vn.huync.smsbackupandrestore;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import vn.huync.smsbackupandrestore.models.SmsModel;
import vn.huync.smsbackupandrestore.others.Utils;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.text.Html;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.nch.smsbackupandrestore.R;

public class ListSmsActivity extends ListActivity {
	
	ArrayList<SmsModel> lSmsByAddress, lSmsReadFromSdcard;
	MyApp myApp;
	ListSmsAdapter adapter;
	String address;
	String filePath;
	
	final int DELETE_SMS_MENU_ITEM = 0;
	final int RESTORE_MENU_ITEM = 1;
	final int CALL_THIS_NUMBER_MENU_ITEM = 2;
	final int SEND_SMS_MENU_ITEM = 3;
	final int DELETE_ALL_SMS_MENU_ITEM = 4;
	final int RESTORE_ALL_MENU_ITEM = 5;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_simple);
		
		myApp = (MyApp)getApplicationContext();
		
		Bundle bundle = getIntent().getExtras();
		address = "";
		if(bundle != null){
			address = bundle.getString("address");
			filePath = getIntent().getExtras().getString("filePath");
		}
		
		lSmsReadFromSdcard = bundle.getParcelableArrayList("smsRead");
		lSmsByAddress = new ArrayList<SmsModel>();
		lSmsByAddress = Utils.ListSmsByAddress(lSmsReadFromSdcard, address);
		
		String contactName = Utils.GetDisplayNameOfAddress(address, myApp.lContact);
		
		adapter = new ListSmsAdapter(this, R.layout.list_simple	, lSmsByAddress, contactName);
		setListAdapter(adapter);
		
		//set title
		String sTitle = contactName;
		if(sTitle != "") sTitle += " ";
		sTitle += "&lt;" + address + "&gt;";
		setTitle(Html.fromHtml(sTitle));
		
		registerForContextMenu(getListView());
		
		AdView adView = (AdView)this.findViewById(R.id.adView);
	    AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
	    adRequestBuilder.addTestDevice("EEB3EC34691D85EFD1DF789EA3776326");
	    adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
	    AdRequest adRequest = adRequestBuilder.build();
	    adView.loadAd(adRequest);
	}
	
	class ListSmsAdapter extends ArrayAdapter<SmsModel>{
		Context context;
		int textViewResourceId;
		List<SmsModel> lSmsByAddress;
		String contactName;
		
		public ListSmsAdapter(Context context, int textViewResourceId,
				List<SmsModel> lSmsByAddress, String contactName) {
			super(context, textViewResourceId, lSmsByAddress);
			this.context = context;
			this.lSmsByAddress = lSmsByAddress;
			this.contactName = contactName;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			if(row == null){
				LayoutInflater inflater = LayoutInflater.from(ListSmsActivity.this);
				row = inflater.inflate(R.layout.row_sms_detail, null);
			}
			
			TextView tName = (TextView) row.findViewById(R.id.row_sms_detail_name);
			TextView tDate = (TextView) row.findViewById(R.id.row_sms_detail_date);
			TextView tContent = (TextView) row.findViewById(R.id.row_sms_detail_content);
			
			
			SmsModel sms = lSmsByAddress.get(position);
			//name
			if(sms.getType() == 1){			//receive
				if(contactName != "")
					tName.setText(Html.fromHtml("<b>" + contactName + " : </b>"));
				else  tName.setText(Html.fromHtml("<b>" + sms.getAddress() + " : </b>"));
			}
			else{							//send
				tName.setText(Html.fromHtml("<b>" + getString(R.string.me) + " : </b>"));
			}
			//date
			final Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(sms.getDate());
			Date date = cal.getTime();
			String sDate = date.getDate() + "/" + date.getMonth() + "/" + (date.getYear()+1900) + " "+
							date.getHours() + ":" + date.getMinutes();

			tDate.setText(sDate);
			
			tContent.setText(sms.getBody());
			
			return row;
		}
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(Menu.NONE, DELETE_SMS_MENU_ITEM, DELETE_SMS_MENU_ITEM, R.string.delete_this_backup_message);
		menu.add(Menu.NONE, RESTORE_MENU_ITEM, RESTORE_MENU_ITEM, R.string.restore_this_message);
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo adapterInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		SmsModel smsSelected = lSmsByAddress.get(adapterInfo.position);
		switch(item.getItemId())
		{
		case DELETE_SMS_MENU_ITEM:
			String addressSelected = smsSelected.getAddress();
			for(Iterator<SmsModel> i = lSmsReadFromSdcard.iterator(); i.hasNext();){
				SmsModel sms = i.next();
				if(PhoneNumberUtils.compare(sms.getAddress(), addressSelected) == true
						&& sms.getDate() == smsSelected.getDate()){
					i.remove();
					lSmsByAddress.remove(sms);
				}
			}
			Utils.WriteFromListToXML(filePath, lSmsReadFromSdcard, null);
			adapter.remove(smsSelected);
			adapter.notifyDataSetChanged();
			break;
		case RESTORE_MENU_ITEM:
			ArrayList<SmsModel> smsNeedWriteToDb = new ArrayList<SmsModel>();
			smsNeedWriteToDb.add(smsSelected);
			int numSmsRestored = Utils.WriteSmsFromListToDb(this, smsNeedWriteToDb, null);
			Utils.ShowToast(this, numSmsRestored + " " + getString(R.string.sms_has_been_restored));
		}
		return super.onContextItemSelected(item);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, CALL_THIS_NUMBER_MENU_ITEM, CALL_THIS_NUMBER_MENU_ITEM, R.string.call_this_contact);
		menu.add(Menu.NONE, SEND_SMS_MENU_ITEM, SEND_SMS_MENU_ITEM, R.string.send_sms_to_this_contact);
		menu.add(Menu.NONE, DELETE_ALL_SMS_MENU_ITEM, DELETE_ALL_SMS_MENU_ITEM, R.string.delete_all_contact_backup_message);
		menu.add(Menu.NONE, RESTORE_ALL_MENU_ITEM, RESTORE_ALL_MENU_ITEM, R.string.restore_this_contact_message);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case CALL_THIS_NUMBER_MENU_ITEM:
				Intent callIntent = new Intent(Intent.ACTION_DIAL);
				callIntent.setData(Uri.parse("tel:"+address));
				startActivity(callIntent);
				break;
			case SEND_SMS_MENU_ITEM:
				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + address)));
				break;
			case DELETE_ALL_SMS_MENU_ITEM:
				String addressSelected = address;
				for(Iterator<SmsModel> i = lSmsReadFromSdcard.iterator(); i.hasNext();){
					SmsModel sms = i.next();
					if(PhoneNumberUtils.compare(sms.getAddress(), addressSelected) == true){
						i.remove();
					}
				}
				Utils.WriteFromListToXML(filePath, lSmsReadFromSdcard, null);
				finish();
				break;
			case RESTORE_ALL_MENU_ITEM:
				ArrayList<SmsModel> smsNeedWriteToDb = new ArrayList<SmsModel>();
				addressSelected = address;
				for(SmsModel sms:lSmsReadFromSdcard){
					if(PhoneNumberUtils.compare(sms.getAddress(), addressSelected) == true){
						smsNeedWriteToDb.add(sms);
					}
				}
				SmsModel.deleteSmsExistInDbFromArray(getApplicationContext(), smsNeedWriteToDb);
				if(smsNeedWriteToDb.size() > 0){
					int numSmsRestored = Utils.WriteSmsFromListToDb(this, smsNeedWriteToDb, null);
					Utils.ShowToast(this, numSmsRestored + " " + getString(R.string.sms_has_been_restored));
				}
				else Utils.ShowToast(this, 0 + " " + getString(R.string.sms_has_been_restored));
				break;
	
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}
}
